<template>
  <div class="create-exercise-set">
    <div class="page-header">
      <h2>Create Exercise Set</h2>
      <div class="header-actions">
        <el-button @click="goBack">
          <el-icon><Back /></el-icon>
          Back
        </el-button>
        <el-button type="primary" @click="saveExerciseSet" :loading="saving" :disabled="!isValid">
          <el-icon><Check /></el-icon>
          Save Exercise Set
        </el-button>
      </div>
    </div>

    <div class="form-container">
      <el-form :model="exerciseSet" label-position="top" :rules="rules" ref="exerciseFormRef">
        <el-card class="form-card">
          <template #header>
            <div class="card-header">
              <h3>Exercise Set Details</h3>
            </div>
          </template>
          
          <el-form-item label="Title" prop="title">
            <el-input v-model="exerciseSet.title" placeholder="Enter a title for your exercise set" />
          </el-form-item>
          
          <el-form-item label="Description" prop="description">
            <el-input 
              v-model="exerciseSet.description" 
              type="textarea" 
              :rows="3"
              placeholder="Describe what this exercise set is about" 
            />
          </el-form-item>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="Category" prop="category">
                <el-select v-model="exerciseSet.category" placeholder="Select a category" style="width: 100%">
                  <el-option label="Programming" value="programming" />
                  <el-option label="Web Development" value="web-development" />
                  <el-option label="Web Design" value="web-design" />
                  <el-option label="Databases" value="databases" />
                  <el-option label="DevOps" value="devops" />
                  <el-option label="Other" value="other" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="Difficulty" prop="difficulty">
                <el-select v-model="exerciseSet.difficulty" placeholder="Select difficulty level" style="width: 100%">
                  <el-option label="Beginner" value="beginner" />
                  <el-option label="Intermediate" value="intermediate" />
                  <el-option label="Advanced" value="advanced" />
                  <el-option label="Expert" value="expert" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-form-item label="Tags" prop="tags">
            <el-tag
              v-for="tag in exerciseSet.tags"
              :key="tag"
              closable
              @close="removeTag(tag)"
              class="tag-item"
            >
              {{ tag }}
            </el-tag>
            <el-input
              v-if="inputTagVisible"
              ref="tagInputRef"
              v-model="inputTagValue"
              class="tag-input"
              size="small"
              @keyup.enter="addTag"
              @blur="addTag"
            />
            <el-button v-else class="button-new-tag" size="small" @click="showTagInput">
              <el-icon><Plus /></el-icon>
              Add Tag
            </el-button>
          </el-form-item>
        </el-card>

        <el-card class="form-card questions-card">
          <template #header>
            <div class="card-header">
              <h3>Questions</h3>
              <el-button type="primary" @click="addQuestion" size="small">
                <el-icon><Plus /></el-icon>
                Add Question
              </el-button>
            </div>
          </template>
          
          <div v-if="exerciseSet.questions.length === 0" class="empty-questions">
            <el-empty description="No questions added yet">
              <el-button type="primary" @click="addQuestion">Add Your First Question</el-button>
            </el-empty>
          </div>
          
          <div v-else class="questions-list">
            <el-collapse v-model="activeQuestions">
              <el-collapse-item 
                v-for="(question, index) in exerciseSet.questions" 
                :key="index"
                :name="index"
              >
                <template #title>
                  <div class="question-header">
                    <span class="question-number">Question {{ index + 1 }}</span>
                    <span class="question-preview">{{ question.text.substring(0, 50) }}{{ question.text.length > 50 ? '...' : '' }}</span>
                  </div>
                </template>
                
                <div class="question-form">
                  <el-form-item :prop="'questions.' + index + '.text'" :rules="{ required: true, message: 'Question text is required', trigger: 'blur' }">
                    <el-input 
                      v-model="question.text" 
                      type="textarea" 
                      :rows="3"
                      placeholder="Enter your question" 
                    />
                  </el-form-item>
                  
                  <div class="question-options">
                    <div v-for="(option, optIndex) in question.options" :key="optIndex" class="option-item">
                      <el-radio v-model="question.correctOption" :label="optIndex" class="option-radio">
                        <el-input 
                          v-model="question.options[optIndex]" 
                          placeholder="Enter option text"
                          class="option-input"
                        />
                      </el-radio>
                      <el-button 
                        type="danger" 
                        circle 
                        size="small" 
                        @click="removeOption(index, optIndex)"
                        :disabled="question.options.length <= 2"
                        class="remove-option-btn"
                      >
                        <el-icon><Delete /></el-icon>
                      </el-button>
                    </div>
                    
                    <div class="option-actions">
                      <el-button type="primary" size="small" @click="addOption(index)" :disabled="question.options.length >= 6">
                        <el-icon><Plus /></el-icon>
                        Add Option
                      </el-button>
                    </div>
                  </div>
                  
                  <div class="question-actions">
                    <el-button type="danger" @click="removeQuestion(index)">
                      <el-icon><Delete /></el-icon>
                      Remove Question
                    </el-button>
                  </div>
                </div>
              </el-collapse-item>
            </el-collapse>
          </div>
        </el-card>
      </el-form>
    </div>
  </div>
</template>

<script>
import { ref, reactive, computed, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { Plus, Delete, Check, Back } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'

export default {
  name: 'CreateExerciseSet',
  components: {
    Plus,
    Delete,
    Check,
    Back
  },
  setup() {
    const router = useRouter()
    const exerciseFormRef = ref(null)
    const tagInputRef = ref(null)
    const inputTagVisible = ref(false)
    const inputTagValue = ref('')
    const activeQuestions = ref([0])
    const saving = ref(false)

    const exerciseSet = reactive({
      title: '',
      description: '',
      category: '',
      difficulty: '',
      tags: [],
      questions: []
    })

    const rules = {
      title: [
        { required: true, message: 'Please enter a title', trigger: 'blur' },
        { min: 3, max: 100, message: 'Length should be 3 to 100 characters', trigger: 'blur' }
      ],
      description: [
        { required: true, message: 'Please enter a description', trigger: 'blur' }
      ],
      category: [
        { required: true, message: 'Please select a category', trigger: 'change' }
      ],
      difficulty: [
        { required: true, message: 'Please select a difficulty level', trigger: 'change' }
      ]
    }

    const isValid = computed(() => {
      return (
        exerciseSet.title &&
        exerciseSet.description &&
        exerciseSet.category &&
        exerciseSet.difficulty &&
        exerciseSet.questions.length > 0 &&
        exerciseSet.questions.every(q => 
          q.text && 
          q.options.length >= 2 && 
          q.options.every(opt => opt.trim() !== '') &&
          q.correctOption !== undefined
        )
      )
    })

    const showTagInput = () => {
      inputTagVisible.value = true
      nextTick(() => {
        tagInputRef.value.focus()
      })
    }

    const addTag = () => {
      if (inputTagValue.value) {
        if (!exerciseSet.tags.includes(inputTagValue.value)) {
          exerciseSet.tags.push(inputTagValue.value)
        }
      }
      inputTagVisible.value = false
      inputTagValue.value = ''
    }

    const removeTag = (tag) => {
      exerciseSet.tags = exerciseSet.tags.filter(t => t !== tag)
    }

    const addQuestion = () => {
      const newQuestionIndex = exerciseSet.questions.length
      exerciseSet.questions.push({
        text: '',
        options: ['', ''],
        correctOption: 0
      })
      activeQuestions.value = [newQuestionIndex]
    }

    const removeQuestion = (index) => {
      ElMessageBox.confirm(
        'Are you sure you want to remove this question?',
        'Warning',
        {
          confirmButtonText: 'Remove',
          cancelButtonText: 'Cancel',
          type: 'warning'
        }
      )
        .then(() => {
          exerciseSet.questions.splice(index, 1)
          // Update active questions
          if (exerciseSet.questions.length > 0 && activeQuestions.value.includes(index)) {
            activeQuestions.value = [Math.max(0, index - 1)]
          }
        })
        .catch(() => {
          // User cancelled
        })
    }

    const addOption = (questionIndex) => {
      exerciseSet.questions[questionIndex].options.push('')
    }

    const removeOption = (questionIndex, optionIndex) => {
      const question = exerciseSet.questions[questionIndex]
      
      // If removing the correct option, reset it to the first option
      if (question.correctOption === optionIndex) {
        question.correctOption = 0
      } 
      // If removing an option before the correct one, adjust the correct option index
      else if (question.correctOption > optionIndex) {
        question.correctOption--
      }
      
      question.options.splice(optionIndex, 1)
    }

    const saveExerciseSet = () => {
      exerciseFormRef.value.validate((valid) => {
        if (valid) {
          saving.value = true
          
          // Here you would normally send the data to your API
          // const payload = { ...exerciseSet }
          // api.createExerciseSet(payload)
          //   .then(response => {
          //     ElMessage.success('Exercise set created successfully')
          //     router.push('/dashboard/exercises')
          //   })
          //   .catch(error => {
          //     console.error('Error creating exercise set:', error)
          //     ElMessage.error('Failed to create exercise set')
          //   })
          //   .finally(() => {
          //     saving.value = false
          //   })
          
          // Mock API call
          setTimeout(() => {
            ElMessage.success('Exercise set created successfully')
            saving.value = false
            router.push('/dashboard/exercises')
          }, 1500)
        } else {
          ElMessage.error('Please fill in all required fields correctly')
          return false
        }
      })
    }

    const goBack = () => {
      router.push('/dashboard/exercises')
    }

    return {
      exerciseFormRef,
      tagInputRef,
      exerciseSet,
      rules,
      inputTagVisible,
      inputTagValue,
      activeQuestions,
      saving,
      isValid,
      showTagInput,
      addTag,
      removeTag,
      addQuestion,
      removeQuestion,
      addOption,
      removeOption,
      saveExerciseSet,
      goBack
    }
  }
}
</script>

<style scoped>
.create-exercise-set {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: var(--el-text-color-primary);
}

.header-actions {
  display: flex;
  gap: 10px;
}

.form-container {
  background-color: var(--el-bg-color);
  border-radius: 4px;
}

.form-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
  font-size: 16px;
}

.tag-item {
  margin-right: 8px;
  margin-bottom: 8px;
}

.tag-input {
  width: 100px;
  margin-right: 8px;
  vertical-align: bottom;
}

.empty-questions {
  padding: 40px 0;
  text-align: center;
}

.question-header {
  display: flex;
  align-items: center;
}

.question-number {
  font-weight: bold;
  margin-right: 10px;
  min-width: 100px;
}

.question-preview {
  color: var(--el-text-color-secondary);
  font-size: 14px;
}

.question-form {
  padding: 10px 0;
}

.question-options {
  margin: 15px 0;
}

.option-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.option-radio {
  flex: 1;
}

.option-input {
  margin-left: 8px;
  width: calc(100% - 30px);
}

.remove-option-btn {
  margin-left: 10px;
}

.option-actions {
  margin-top: 10px;
}

.question-actions {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style> 